package com.kingray.openfire.plugin.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.jivesoftware.util.JiveGlobals;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.xmpp.packet.Message;
import org.xmpp.packet.Message.Type;
import org.xmpp.packet.Packet;
import org.jivesoftware.admin.AuthCheckFilter;
import org.jivesoftware.openfire.OfflineMessage;
import org.jivesoftware.openfire.OfflineMessageStore;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.user.UserManager;
import org.jivesoftware.openfire.user.UserNotFoundException;

import com.kingray.openfire.plugin.KingrayServicePlugin;
import com.kingray.openfire.plugin.dao.MessageDAO;
import com.kingray.openfire.plugin.dao.impl.MessageDAOImpl;
import com.kingray.openfire.plugin.vo.MessagePreviewVO;
import com.kingray.openfire.plugin.vo.MessageVO;
import com.kingray.openfire.plugin.vo.PageVO;
import com.xiongyingqi.util.DomainHelper;

public class MessageServiceServlet extends HttpServlet {
	public static final Logger log = LoggerFactory
			.getLogger(MessageServiceServlet.class);
	private KingrayServicePlugin plugin;
	private MessageDAO messageDAO = new MessageDAOImpl();

	private UserManager userManager; // 用户管理
	private String xmppDomain; // xmpp服务名
	private static final String TOS_STRING_TOKENIZER = new String(";");// 接受者分隔符标识

	// private ComponentManager componentManager;
	// @Override
	// public void shutdown() {
	//
	// }
	// @Override
	// public void start() {
	// }
	// @Override
	// public String getDescription() {
	// return null;
	// }
	// @Override
	// public String getName() {
	// return null;
	// }
	// @Override
	// public void processPacket(Packet arg0) {
	//
	// }
	// @Override
	// public void initialize(JID arg0, ComponentManager arg1)
	// throws ComponentException {
	//
	// }

	/**
	 * 默认构造方法
	 */
	public MessageServiceServlet() {
		// this.componentManager =
		// ComponentManagerFactory.getComponentManager();
		this.userManager = UserManager.getInstance();
		this.xmppDomain = JiveGlobals.getProperty("xmpp.domain");
		log.debug("this.xmppDomain ========= " + this.xmppDomain);

	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		log.debug("MessageServiceServlet init ------------ ");
		plugin = (KingrayServicePlugin) XMPPServer.getInstance()
				.getPluginManager().getPlugin("kingrayplugin");
		AuthCheckFilter.addExclude("kingrayplugin/messageservice");

		// InterceptorManager.getInstance().addInterceptor(messageHistoryListener);
	}

	@Override
	public void destroy() {
		super.destroy();
		AuthCheckFilter.removeExclude("kingrayplugin/messageservice");
	}

	/**
	 * 发送消息
	 * 
	 * @param from
	 * @param to
	 * @param body
	 * @param chat
	 */
	private void sendMessage(String from, String to, String subject,
			String body, Type chat) {
		Message message = new Message();
		if (!to.contains("@")) { // 如果发送的消息不包含服务名，那么自动加上本服务的服务名
			StringBuilder builder = new StringBuilder(to);
			builder.append("@");
			builder.append(xmppDomain);
			to = builder.toString();
		}
		if (!from.contains("@")) { // 如果发送的消息不包含服务名，那么自动加上本服务的服务名
			StringBuilder builder = new StringBuilder(from);
			builder.append("@");
			builder.append(xmppDomain);
			from = builder.toString();
		}
		message.setFrom(from);
		message.setTo(to);
		if (subject != null) {
			message.setSubject(subject);
		}
		message.setBody(body);
		message.setType(chat);
		// JID jid = new JID(node, domain, resource);
		this.sendMessage(message);
	}

	private void getMessageHistory(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PageVO inputPageVO = new PageVO();
		MessageVO messageVO = new MessageVO();
		String messageFrom = request.getParameter("messageFrom");
		String messageTo = request.getParameter("messageTo");
		if ((messageFrom == null || "".equals(messageFrom))
				&& (messageTo == null || "".equals(messageTo))) {
			replyMessage("MissRequiredParameter:from or to", response);
			return;
		}
		String messageBody = request.getParameter("messageBody");
		String messageSubject = request.getParameter("messageSubject");
		String pageNumberStr = request.getParameter("pageNumber");
		String pageSizeStr = request.getParameter("pageSize");
		// 页数
		int pageNumber = 1;
		// 每页的大小
		int pageSize = 20;

		if (pageNumberStr != null) {
			try {
				pageNumber = Integer.parseInt(pageNumberStr);
			} catch (NumberFormatException e) {
				log.warn(pageNumber + "");
				log.warn(e.getMessage());
			}
		}
		if (pageSizeStr != null) {
			try {
				pageSize = Integer.parseInt(pageSizeStr);
			} catch (NumberFormatException e) {
				log.warn(pageSize + "");
				log.warn(e.getMessage());
			}
		}

		String dateFrom = request.getParameter("dateFrom");
		if (dateFrom != null) {
			dateFrom += " 00:00:00";
		}
		String dateTo = request.getParameter("dateTo");
		if (dateTo != null) {
			dateTo += " 23:59:59";
		}

		String[] orderBys = request.getParameterValues("orderBy");
		int asc = 1;
		String ascStr = request.getParameter("asc");
		if (ascStr != null && !"".equals(ascStr)) {
			try {
				asc = Integer.parseInt(ascStr);
			} catch (NumberFormatException e) {
				log.error(e.getMessage(), e);
			}
		}

		messageVO.setMessageFrom(messageFrom);
		messageVO.setMessageTo(messageTo);
		messageVO.setMessageSubject(messageSubject);
		messageVO.setMessageBody(messageBody);

		inputPageVO.setPageSize(pageSize);
		inputPageVO.setPageNumber(pageNumber);
		
		
		PageVO result = messageDAO.getMessageHistory(inputPageVO, messageVO,
				dateFrom, dateTo, orderBys, asc);

		JsonConfig config = new JsonConfig();
		config.setExcludes(new String[] { "messageDateTime" });
		JSONArray jsonArray = JSONArray.fromObject(result, config);
		try {
			response.setContentType("text/plain;charset=UTF-8");
//			response.setContentType("text/html;charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");// 没有缓存，立即返回响应
			PrintWriter out = response.getWriter();
			out.print(jsonArray);// 不能用println
			// System.out.println("jsonArray ====== " + jsonArray);
			out.flush();
			out.close();
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
	}
	/**
	 * 根据用户名查询历史记录
	 * @param request
	 * @param response
	 */
	private void getMessageHistoryByUserName(HttpServletRequest request,
			HttpServletResponse response) {
		PageVO inputPageVO = new PageVO();
		MessageVO messageVO = new MessageVO();
		String userName = request.getParameter("userName"); // 用户名
		String relationUserName = request.getParameter("relationUserName"); // 关联用户
		if ((userName == null || "".equals(userName))) {
			replyMessage("MissRequiredParameter:userName", response);
			return;
		}
		String messageBody = request.getParameter("messageBody");
		String messageSubject = request.getParameter("messageSubject");
		String pageNumberStr = request.getParameter("pageNumber");
		String pageSizeStr = request.getParameter("pageSize");
		// 页数
		int pageNumber = 1;
		// 每页的大小
		int pageSize = 20;

		if (pageNumberStr != null) {
			try {
				pageNumber = Integer.parseInt(pageNumberStr);
			} catch (NumberFormatException e) {
				log.warn(pageNumber + "");
				log.warn(e.getMessage());
			}
		}
		if (pageSizeStr != null) {
			try {
				pageSize = Integer.parseInt(pageSizeStr);
			} catch (NumberFormatException e) {
				log.warn(pageSize + "");
				log.warn(e.getMessage());
			}
		}

		String dateFrom = request.getParameter("dateFrom");
		if (dateFrom != null) {
			dateFrom += " 00:00:00";
		}
		String dateTo = request.getParameter("dateTo");
		if (dateTo != null) {
			dateTo += " 23:59:59";
		}

		String[] orderBys = request.getParameterValues("orderBy");
		int asc = 1;
		String ascStr = request.getParameter("asc");
		if (ascStr != null && !"".equals(ascStr)) {
			try {
				asc = Integer.parseInt(ascStr);
			} catch (NumberFormatException e) {
				log.error(e.getMessage(), e);
			}
		}

		messageVO.setMessageSubject(messageSubject);
		messageVO.setMessageBody(messageBody);

		inputPageVO.setPageSize(pageSize);
		inputPageVO.setPageNumber(pageNumber);

		PageVO result = messageDAO.getMessageHistoryByUserName(inputPageVO, messageVO, 
				dateFrom, dateTo, userName, relationUserName, orderBys, asc);

		JsonConfig config = new JsonConfig();
		config.setExcludes(new String[] { "messageDateTime" });
		JSONArray jsonArray = JSONArray.fromObject(result, config);
		try {
			response.setContentType("text/plain;charset=UTF-8");
//			response.setContentType("text/html;charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");// 没有缓存，立即返回响应
			PrintWriter out = response.getWriter();
			out.print(jsonArray);// 不能用println
			// System.out.println("jsonArray ====== " + jsonArray);
			out.flush();
			out.close();
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
	}
	private void getMessageHistoryByMessageId(HttpServletRequest request,
			HttpServletResponse response) {
		String messageIdStr = request.getParameter("messageId");
		if(messageIdStr != null){
			try {
				long messageId = Long.parseLong(messageIdStr);
				MessageVO messageVO = messageDAO.getMessageHistoryByMessageId(messageId);
				JSONObject jsonObject = JSONObject.fromObject(messageVO);
				try {
					response.setContentType("text/plain;charset=UTF-8");
//					response.setContentType("text/html;charset=UTF-8");
					response.setHeader("Cache-Control", "no-cache");// 没有缓存，立即返回响应
					PrintWriter out = response.getWriter();
					out.print(jsonObject);// 不能用println
					out.flush();
					out.close();
				} catch (IOException e) {
					log.error(e.getMessage(), e);
				}
			} catch (NumberFormatException e) {
				replyMessage("MissTheRequiredParameter: messageId", response);
			}
		} else {
			replyMessage("MissTheRequiredParameter: messageId", response);
		}
	}
	private void getOfflineMessageByTime(HttpServletRequest request,
			HttpServletResponse response) {
		String userName = request.getParameter("userName");
		String time = request.getParameter("time");
		try {
			OfflineMessage offlineMessage = OfflineMessageStore.getInstance().getMessage(userName, new Date(Long.parseLong(time)));
			MessageVO messageVO = new MessageVO();
			messageVO.setMessageFrom(DomainHelper.removeDomain(offlineMessage.getFrom().toString()));
			messageVO.setMessageFrom(DomainHelper.removeDomain(offlineMessage.getTo().toString()));
			messageVO.setMessageSubject(offlineMessage.getSubject());
			messageVO.setMessageBody(offlineMessage.getBody());
			messageVO.setMessageDateTime(offlineMessage.getCreationDate());
			JSONObject jsonObject = JSONObject.fromObject(messageVO);
			try {
				response.setContentType("text/plain;charset=UTF-8");
//				response.setContentType("text/html;charset=UTF-8");
				response.setHeader("Cache-Control", "no-cache");// 没有缓存，立即返回响应
				PrintWriter out = response.getWriter();
				out.print(jsonObject);// 不能用println
				// System.out.println("jsonArray ====== " + jsonArray);
				out.flush();
				out.close();
			} catch (IOException e) {
				log.error(e.getMessage(), e);
			}
		} catch (Exception e) {
			replyMessage("NoSuchOfflineMessage", response);
		}
		
	}
	/**
	 * 发送广播通知
	 * 
	 * @param from
	 * @param to
	 * @param body
	 */
	private void sendNotification(String from, String to, String subject,
			String body) {
		Message message = new Message();
		if (!to.contains("@")) { // 如果发送的消息不包含服务名，那么自动加上本服务的服务名
			StringBuilder builder = new StringBuilder(to);
			builder.append("@");
			builder.append(xmppDomain);
			to = builder.toString();
		}
		if (!from.contains("@")) { // 如果发送的消息不包含服务名，那么自动加上本服务的服务名
			StringBuilder builder = new StringBuilder(from);
			builder.append("@");
			builder.append(xmppDomain);
			from = builder.toString();
		}
		message.setFrom(from);
		message.setTo(to);
		if (subject != null) {
			message.setSubject(subject);
		}
		message.setBody(body);
		message.setType(Message.Type.normal);
		// JID jid = new JID(node, domain, resource);
		this.sendMessage(message);
	}

	private static int messageIdIndex;

	/**
	 * 返回唯一id
	 * 
	 * @return
	 */
	private String randomMessageId() {
		StringBuilder builder = new StringBuilder();
		builder.append(System.currentTimeMillis());
		builder.append(messageIdIndex++);
		return builder.toString();
	}

	/**
	 * 发送消息
	 * 
	 * @param message
	 */
	public void sendMessage(Message message) {
		// componentManager.sendPacket(this, message);
		message.setID(randomMessageId());
		log.debug(message.toString());
		XMPPServer.getInstance().getMessageRouter().route(message);
	}

	/**
	 * 判断用户是否存在
	 * 
	 * @param userName
	 * @return
	 */
	private boolean isExistUser(String userName) {
		try {
			userManager.getUser(userName);
		} catch (UserNotFoundException e) {
			log.error("userName: " + userName);
			log.error(e.getMessage(), e);
			return false;
		}
		return true;
	}

	/**
	 * 发送消息
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doSendMessage(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String from = request.getParameter("messageFrom");
		// String to = request.getParameter("to");
		String[] tos = request.getParameterValues("messageTo");
		String body = request.getParameter("messageBody");

		String subject = request.getParameter("messageSubject");
		String actionType = request.getParameter("actionType");
		String PAGE_LOAD = "ok";
		for (int i = 0; i < tos.length; i++) {
			String tot = tos[i];
			StringTokenizer tokenizer = new StringTokenizer(tot,
					TOS_STRING_TOKENIZER);
			while (tokenizer.hasMoreTokens()) {
				String to = tokenizer.nextToken();
				if (isExistUser(to)) {
					if ("sendMessage".equals(actionType)) {
						sendMessage(from, to, subject, body, Message.Type.chat);
					} else if ("sendNotification".equals(actionType)) {
						sendMessage(from, to, subject, body,
								Message.Type.normal);
					}
				} else {
					PAGE_LOAD = "there is someone not exist";
				}
			}
		}
		request.setAttribute("PAGE_LOAD", PAGE_LOAD);
		replyMessage(PAGE_LOAD, response);
		// response.sendRedirect("messageService.jsp");
	}

	/**
	 * 获取离线消息数
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void getOfflineMessageCount(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String userName = request.getParameter("userName");
		int count = 0;
		if (userName != null && !"".equals(userName)) {
			count = OfflineMessageStore.getInstance()
					.getMessages(userName, false).size();
		}
		try {
			response.setContentType("text/plain;charset=UTF-8");
			// response.setContentType("text/html;charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");// 没有缓存，立即返回响应
			PrintWriter out = response.getWriter();
			out.print(count);// 不能用println
			// System.out.println("jsonArray ====== " + jsonArray);
			out.flush();
			out.close();
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
	}

	/**
	 * 获取离线消息
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void getOfflineMessage(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String userName = request.getParameter("userName");
		if (userName != null && !"".equals(userName)) {
			Collection<OfflineMessage> offlineMessages = OfflineMessageStore
					.getInstance().getMessages(userName, false);
			Collection<MessageVO> messageVOs = new ArrayList<MessageVO>();
			Iterator<OfflineMessage> iterator = offlineMessages.iterator();
			for (; iterator.hasNext();) {
				OfflineMessage offlineMessage = (OfflineMessage) iterator
						.next();
				MessageVO messageVO = new MessageVO();
				messageVO.setSendMessageId(offlineMessage.getID());
				messageVO.setMessageDateTime(offlineMessage.getCreationDate());
				messageVO.setMessageFrom(DomainHelper
						.removeDomain(offlineMessage.getFrom().toString()));
				messageVO.setMessageTo(DomainHelper.removeDomain(offlineMessage
						.getTo().toString()));
				messageVO.setMessageSubject(offlineMessage.getSubject());
				messageVO.setMessageBody(offlineMessage.getBody());
				messageVOs.add(messageVO);
			}
//			JsonConfig config = new JsonConfig();
//			config.setExcludes(new String[] { "messageDateTime" });
			JSONArray jsonArray = JSONArray.fromObject(messageVOs);
			try {
				response.setContentType("text/plain;charset=UTF-8");
//				response.setContentType("application/x-javascript");
				// response.setContentType("text/html;charset=UTF-8");
				response.setHeader("Cache-Control", "no-cache");// 没有缓存，立即返回响应
				PrintWriter out = response.getWriter();
				out.print(jsonArray);// 不能用println
				// System.out.println("jsonArray ====== " + jsonArray);
				out.flush();
				out.close();
			} catch (IOException e) {
				log.error(e.getMessage(), e);
			}
		} else {
			replyMessage("IncorrectParameters: userName", response);
		}
	}
	/**
	 * 获取用户未读消息预览
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void getOfflineMessagePreview(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String userName = request.getParameter("userName");
		if (userName != null && !"".equals(userName)) {
			Collection<OfflineMessage> offlineMessages = OfflineMessageStore
					.getInstance().getMessages(userName, false); // 获取所有离线消息
			Collection<MessagePreviewVO> messagePreviewVOs = new ArrayList<MessagePreviewVO>();
			Iterator<OfflineMessage> iterator = offlineMessages.iterator();
			Map<String, ArrayList<String>> fromAndMessageMap = new LinkedHashMap<String, ArrayList<String>>();
			for (; iterator.hasNext();) {
				OfflineMessage offlineMessage = (OfflineMessage) iterator.next();
				String from = DomainHelper.removeDomain(offlineMessage.getFrom().toString());
				ArrayList messageList = fromAndMessageMap.get(from);
				if(messageList == null){
					messageList = new ArrayList<String>();
				}
				messageList.add(offlineMessage.getBody());
				fromAndMessageMap.put(from, messageList);
			}
//			JsonConfig config = new JsonConfig();
//			config.setExcludes(new String[] { "messageDateTime" });
			JSONArray jsonArray = JSONArray.fromObject(messagePreviewVOs);
			try {
				response.setContentType("text/plain;charset=UTF-8");
//				response.setContentType("application/x-javascript");
				// response.setContentType("text/html;charset=UTF-8");
				response.setHeader("Cache-Control", "no-cache");// 没有缓存，立即返回响应
				PrintWriter out = response.getWriter();
				out.print(jsonArray);// 不能用println
				// System.out.println("jsonArray ====== " + jsonArray);
				out.flush();
				out.close();
			} catch (IOException e) {
				log.error(e.getMessage(), e);
			}
		} else {
			replyMessage("IncorrectParameters: userName", response);
		}
	
	}
	/**
	 * 分页获取离线消息
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void getOfflineMessagePageInfo(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String userName = request.getParameter("userName");
		String pageNumberStr = request.getParameter("pageNumber");
		String pageSizeStr = request.getParameter("pageSize");
		
		int pageSize = 20;
		int pageNumber = 1;
		if(pageNumberStr != null && !"".equals(pageNumberStr)){
			pageNumber = Integer.parseInt(pageNumberStr);
		}
		
		if (userName != null && !"".equals(userName)) {
			Collection<OfflineMessage> offlineMessages = OfflineMessageStore
					.getInstance().getMessages(userName, false);
			Collection<MessageVO> messageVOs = new ArrayList<MessageVO>();
			Iterator<OfflineMessage> iterator = offlineMessages.iterator();
			for (; iterator.hasNext();) {
				OfflineMessage offlineMessage = (OfflineMessage) iterator
						.next();
				MessageVO messageVO = new MessageVO();
				messageVO.setSendMessageId(offlineMessage.getID());
				messageVO.setMessageDateTime(offlineMessage.getCreationDate());
				messageVO.setMessageFrom(DomainHelper
						.removeDomain(offlineMessage.getFrom().toString()));
				messageVO.setMessageTo(DomainHelper.removeDomain(offlineMessage
						.getTo().toString()));
				messageVO.setMessageSubject(offlineMessage.getSubject());
				messageVO.setMessageBody(offlineMessage.getBody());
				messageVOs.add(messageVO);
			}
//			JsonConfig config = new JsonConfig();
//			config.setExcludes(new String[] { "messageDateTime" });
			JSONArray jsonArray = JSONArray.fromObject(messageVOs);
			try {
				response.setContentType("text/plain;charset=UTF-8");
//				response.setContentType("application/x-javascript");
				// response.setContentType("text/html;charset=UTF-8");
				response.setHeader("Cache-Control", "no-cache");// 没有缓存，立即返回响应
				PrintWriter out = response.getWriter();
				out.print(jsonArray);// 不能用println
				// System.out.println("jsonArray ====== " + jsonArray);
				out.flush();
				out.close();
			} catch (IOException e) {
				log.error(e.getMessage(), e);
			}
		} else {
			replyMessage("IncorrectParameters: userName", response);
		}
	}
	
	private void doShowOfflineMessagePage(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String userName = request.getParameter("userName");
		if (userName != null && !"".equals(userName)) {
			Collection<OfflineMessage> offlineMessages = OfflineMessageStore
					.getInstance().getMessages(userName, false);
			Collection<MessageVO> messageVOs = new ArrayList<MessageVO>();
			Iterator<OfflineMessage> iterator = offlineMessages.iterator();
			for (; iterator.hasNext();) {
				OfflineMessage offlineMessage = (OfflineMessage) iterator
						.next();
				MessageVO messageVO = new MessageVO();
				messageVO.setSendMessageId(offlineMessage.getID());
				messageVO.setMessageDateTime(offlineMessage.getCreationDate());
				messageVO.setMessageFrom(DomainHelper
						.removeDomain(offlineMessage.getFrom().toString()));
				messageVO.setMessageTo(DomainHelper.removeDomain(offlineMessage
						.getTo().toString()));
				messageVO.setMessageSubject(offlineMessage.getSubject());
				messageVO.setMessageBody(offlineMessage.getBody());
				messageVOs.add(messageVO);
			}
//			JsonConfig config = new JsonConfig();
//			config.setExcludes(new String[] { "messageDateTime" });
			JSONArray jsonArray = JSONArray.fromObject(messageVOs);
			request.getSession().setAttribute("jsonOfflineMessages", jsonArray);
			response.sendRedirect("pages/offline_message.jsp");
		} else {
			replyMessage("IncorrectParameters: userName", response);
		}
	}
	
	/**
	 * 将离线消息设为已读，要删除消息，必须传入用户名和长整型数字表示的时间
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void markReadOfflineMessage(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String timeStr = request.getParameter("time");
		String userName = request.getParameter("userName");
		if(userName != null && !"".equals(userName) && timeStr != null && !"".equals(timeStr)) {
			try{
				long time = Long.parseLong(timeStr);
				Date creationDate = new Date(time);
				OfflineMessageStore.getInstance().deleteMessage(userName, creationDate);
				replyMessage("ok", response);
			} catch (NumberFormatException e) {
				log.error(e.getMessage(), e);
			}
		} else {
			replyMessage("IncorrectParameters: userName or time", response);
		}
	}
	

	private void replyMessage(String message, HttpServletResponse response) {
		PrintWriter out;
		try {
			out = response.getWriter();
			response.setContentType("text/plain");
			out.print(message);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取新消息
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void showUserNotificationPage(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String userName = request.getParameter("userName");
		request.getSession().setAttribute("userName", userName);
		response.sendRedirect("pages/notification.jsp");
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if(!plugin.validate(request, response)){
			return;
		}
		String actionType = request.getParameter("actionType");
		log.debug(" ------------- MessageServiceServlet doPost ------------- ");
		log.debug("actionType ============ " + actionType);
		if ("sendMessage".equals(actionType)) {
			doSendMessage(request, response);
		} else if ("sendNotification".equals(actionType)) {
			doSendMessage(request, response);
			// doSendNotification(request, response);
		} else if ("getMessageHistory".equals(actionType)) {
			getMessageHistory(request, response);
		} else if ("getMessageHistoryByUserName".equals(actionType)) {
			getMessageHistoryByUserName(request, response);
		} else if ("getOfflineMessage".equals(actionType)) {
			getOfflineMessage(request, response);
		} else if ("markReadOfflineMessage".equals(actionType)) {
			markReadOfflineMessage(request, response);
		} else if ("getOfflineMessageCount".equals(actionType)) {
			getOfflineMessageCount(request, response);
		} else if ("showOfflineMessagePage".equals(actionType)) {
			doShowOfflineMessagePage(request, response);
		} else if("showUserNotificationPage".equals(actionType)){
			showUserNotificationPage(request, response);
		} else if("getOfflineMessageByTime".equals(actionType)){
			getOfflineMessageByTime(request, response);
		} else if("getMessageHistoryByMessageId".equals(actionType)){
			getMessageHistoryByMessageId(request, response);
		} else {
			replyMessage("IncorrectParameters: actionType", response);
		}
	}



	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}
	public static void main(String[] args) {
		System.out.println(new Date(1365645707707L));
	}

}
